//
//  SearchProject.m
//  HappyStore
//
//  Created by 点点充 on 16/1/16.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "SearchProject.h"
#import "SearchProjectCell.h"
#import "SearchProjectInfoVC.h"
#import "SearchProjectShaiXuan.h"

#import "LSBecomeVIPVC.h"
#import "LSRechargeVC.h"
#import "ForgetPassWord.h"
#import "LSPayResultVC.h"
@interface SearchProject ()

{
    NSMutableArray *_aryInfo;
    NSInteger paggge;
    
    NSMutableDictionary *muDicParameters;
    
    NSString *strProjectId;
    
    NSString * seguStr;
    NSString * or_Number;
    BOOL  isSetPayPass;
    NSString * projectId;
    double price;
}
@property (strong, nonatomic) LSPromptAlertVC * LSPromptAlert;
@end

@implementation SearchProject

#pragma mark - 初始化

-(LSPromptAlertVC *)LSPromptAlert{
    
    if (!_LSPromptAlert) {
        _LSPromptAlert = [[LSPromptAlertVC alloc]init];
    }
    return _LSPromptAlert;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;

    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];


}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"找项目";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStylePlain target:self action:@selector(btnClickRight)];
    rightBar.tintColor = RGB(45, 45, 45);
    self.navigationItem.rightBarButtonItem = rightBar;
   //================
    if (self.searchStr) {
        
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];//页码
        [muDicParameters setObject:self.searchStr forKey:@"industry"];//类型
        [self startSearch];
        
    }else{
        
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];//页码
        //        [muDicParameters setObject:self.searchStr forKey:@"title"];//类型
        [self startSearch];
        
    }
//========
    //取消返回的文字
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
    
    
    _aryInfo = [NSMutableArray array];
    paggge = 1;
    
    
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (_aryInfo.count != 0) {
            if ([[USER_DEFAULTS objectForKey:@"isOpenSound"] boolValue]) {//声音开关
                NSString *path = [[NSBundle mainBundle]pathForResource:@"refresh"
                                                                ofType:@"wav"];
                
                SystemSoundID soundID;
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
                
                AudioServicesPlaySystemSound(soundID); //仅播放音频
            }
            paggge = 1;
            [muDicParameters setObject:@"1" forKey:@"page"];
            [self startSearch];
        }else {
            [_mainTableView.mj_header endRefreshing];
        }
    }];
    
    
    
    _mainTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        paggge += 1;
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];
        [self startSearch];
    }];
    
    _mainTableView.mj_footer.hidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ShaiXuanSearch:) name:@"SearchProjectShaiXuanNoti" object:nil];
    

    if (muDicParameters == nil) {
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:@"1" forKey:@"page"];
    }
    
    [self showRoundProgressWithTitle:@"请稍后..."];
//    [self startSearch];
    
    self.mainSearchBar.layer.borderWidth = 1.f;
    self.mainSearchBar.layer.borderColor = [RGB(235, 235, 235) CGColor];

    self.mainSearchBar.delegate = self;

    
    // 设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    //监听按钮
    [self.LSPromptAlert.PromptAlertView.becomeVIPBtn addTarget:self action:@selector(clickBecomeVIPBtn) forControlEvents:UIControlEventTouchUpInside];
    
    [self.LSPromptAlert.PromptAlertView.alipayBtn addTarget:self action:@selector(clickAlipayBtn) forControlEvents:UIControlEventTouchUpInside];
    
    [self.LSPromptAlert.PromptAlertView.balancePayBtn addTarget:self action:@selector(clickCashBtn) forControlEvents:UIControlEventTouchUpInside];
    
    //支付回调通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentView) name:@"alipayResult" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentFailedView) name:@"alipayFailed" object:nil];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}
-(void)leftBarButtonItemClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 接收筛选到数据
- (void)ShaiXuanSearch:(NSNotification *)dic

{
    muDicParameters = [NSMutableDictionary dictionaryWithDictionary:dic.userInfo];
    //NSLog(@"mu:%@",muDicParameters[@"industry"]);
    [self startSearch];
    
}

/**
 *  @author LLJ, 16-01-16 17:01:06
 *
 *  rightBarClick
 */
- (void)btnClickRight
{
    //取消显示后退键文字
    //UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    //self.navigationItem.backBarButtonItem = barButtonItem;
    SearchProjectShaiXuan *sVC = [[SearchProjectShaiXuan alloc] init];
    
    [self.navigationController pushViewController:sVC animated:YES];
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    if (_aryInfo.count != 0) {
        _aryInfo = [NSMutableArray array];
        [_mainTableView reloadData];
    }
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
   
    
    if (searchBar.text.length == 0) {
        return YES;
    }else {
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];//页码
        [muDicParameters setObject:searchBar.text forKey:@"title"];//类型
        [self startSearch];
        return YES;
    }
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //NSLog(@"-----%@",searchBar.text);
    if (searchBar.text.length != 0) {
        [searchBar resignFirstResponder];
        paggge = 1;
        muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[NSString stringWithFormat:@"%ld",paggge] forKey:@"page"];//页码
        [muDicParameters setObject:searchBar.text forKey:@"title"];//类型
        [self startSearch];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:_aryInfo.count];
    return _aryInfo.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    return 103;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *cellLoveSingle = @"cellSingle";
    //注册
    UINib * nib = [UINib nibWithNibName:@"SearchProjectCell" bundle:nil];
    
    [tableView registerNib:nib forCellReuseIdentifier:cellLoveSingle];
    SearchProjectCell *cell = [tableView dequeueReusableCellWithIdentifier:cellLoveSingle];
    tableView.rowHeight = UITableViewAutomaticDimension;
    
    if (!cell) {
        cell = [[SearchProjectCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellLoveSingle];
    }
    
    cell.TitleLabel.text = _aryInfo[indexPath.row][@"title"];
    
    cell.AddressLabel.text = _aryInfo[indexPath.row][@"address"];
    
    cell.IndustryLabel.text = _aryInfo[indexPath.row][@"industry"];
    
    cell.PriceLabel.text = [CustomExcetion comperNumber:_aryInfo[indexPath.row][@"investment"]];
 
    if ([_aryInfo[indexPath.row][@"type"] isEqualToString:@"政府"]) {
        
        cell.ProjectIconImageView.image = [UIImage imageNamed:@"政府"];
    }else if ([_aryInfo[indexPath.row][@"type"] isEqualToString:@"企业"]){
        
        cell.ProjectIconImageView.image = [UIImage imageNamed:@"企业"];
    }else{
        
        cell.ProjectIconImageView.image = [UIImage imageNamed:@"个人"];
    }

    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (allConstMemberid) {
        [self showRoundProgressWithTitle:@"请稍后..."];
        
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        dict[@"projectId"] = _aryInfo[indexPath.row][@"projectId"];
        dict[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
        
        [LSHttpTool sendHttpData:@"projectDetail_app_project.im" params:dict success:^(id responseObject) {
            [self hideBubble];
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
            
            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                
                [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
                
                SearchProjectInfoVC * SeaVC = [[SearchProjectInfoVC alloc]initWithNibName:@"SearchProjectInfoVC" bundle:nil];
                SeaVC.dataDict = dicInfo[@"data"];
                SeaVC.projectData = [NSMutableArray arrayWithArray:dicInfo[@"data"][@"commentsList"]];
                
                [self.navigationController pushViewController:SeaVC animated:YES];
                
            }else if ([[dicInfo objectForKey:@"result"] integerValue] == 2){
                

                [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
                
            }else if ([[dicInfo objectForKey:@"result"]integerValue] == 3){
                
                isSetPayPass = [dicInfo[@"data"][@"isSetPayPass"] boolValue];
                price = [dicInfo[@"data"][@"powerMoney"]floatValue];
                
                projectId = _aryInfo[indexPath.row][@"projectId"];
                self.LSPromptAlert.modalPresentationStyle=UIModalPresentationOverCurrentContext;
                [self presentViewController:self.LSPromptAlert animated:YES completion:nil];
                
            }
            
            
        } failure:^(NSError *error) {

            [self showSingleIconBubble:@"网络连接错误"];
            
        }];
        
    }else{
    
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        
        alert.tag = 10;
        
        [alert show];
    
    }
    
}

#pragma mark - 弹框按钮监听
//跳转会员界面
-(void)clickBecomeVIPBtn{
    
    [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
    
    LSBecomeVIPVC * LSBecomeVIP = [[LSBecomeVIPVC alloc]init];
    [self.navigationController pushViewController:LSBecomeVIP animated:YES];
    
}

#pragma mark - 支付回调通知
-(void)clickAlipayBtn{
    
    or_Number = [LSAlipay alipay:@"乐商网" body:@"项目详情" price:price];
    
}

-(void)presentFailedView{
    
    // 跳转至支付失败页面
    LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
    [LSPayResult setCashTypeWithCashFailed];
    [self.navigationController pushViewController:LSPayResult animated:YES];
    
}

-(void)presentView{
    
    [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
    [self showRoundProgressWithTitle:@"请稍后..."];
    
    NSMutableDictionary * dic = [NSMutableDictionary  dictionary];
    dic[@"token"] = allConstMemberToken;
    dic[@"payUserId"] = allConstMemberid;
    dic[@"payWay"] = @"2";
    dic[@"payMoney"] = @(price);
    dic[@"resId"] = projectId;
    dic[@"order_no"] = or_Number;
    
    [LSHttpTool sendHttpData:@"buyProjectDetail_app_pay.im.lensum" params:dic success:^(id responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];

        [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
  
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            NSMutableDictionary * dict = [NSMutableDictionary dictionary];
            dict[@"projectId"] = dic[@"resId"];
            dict[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
            
            [LSHttpTool sendHttpData:@"projectDetail_app_project.im" params:dict success:^(id responseObject) {
                if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {

                    SearchProjectInfoVC * SeaVC = [[SearchProjectInfoVC alloc]initWithNibName:@"SearchProjectInfoVC" bundle:nil];
                    SeaVC.dataDict = responseObject[@"data"];
                    SeaVC.projectData = [NSMutableArray arrayWithArray:responseObject[@"data"][@"commentsList"]];
                    
                    [self.navigationController pushViewController:SeaVC animated:YES];
                    
                    [self hideBubble];
                    
                }else{

                    [self showSingleIconBubble:dicInfo[@"msg"]];
                    
                }
                
            } failure:^(NSError *error) {

                [self showSingleIconBubble:@"网络连接错误"];
                
            }];
            
        }else{

           [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
            
        }
        
    } failure:^(NSError *error) {
        
        // 跳转至支付成功页面
        LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
        [LSPayResult setCashTypeWithExchangeFailed];
        
        [self hideBubble];
    }];
    
}

#pragma mark - 余额支付
-(void)clickCashBtn{
    
    NSString * balanceStr = [self.LSPromptAlert.PromptAlertView.balanceLabel.text stringByReplacingOccurrencesOfString:@"￥"withString:@""];
    
    double balance = [balanceStr floatValue];
    
    if (balance < 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付失败"
                                                        message:@"余额不足！"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"立刻充值",nil];
        alert.tag = 20;
        [alert show];
        
    }else{
        
        if (isSetPayPass) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付失败"
                                                            message:@"未设置支付密码"
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:@"立即设置",nil];
            alert.tag = 30;
            [alert show];
            
        }else{
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"余额支付" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alert.alertViewStyle = UIAlertViewStylePlainTextInput;
            
            UITextField *title = [alert textFieldAtIndex:0];
            [title setSecureTextEntry:YES];
            title.borderStyle = UITextBorderStyleNone;
            title.textColor = [UIColor redColor];
            title.textAlignment = NSTextAlignmentCenter;
            title.font = [UIFont systemFontOfSize:16.0f];
            title.placeholder = @"请输入支付密码";
            
            
            [alert showAlertWithCompletionHandler:^(NSInteger buttonIndex) {
                if(buttonIndex == 1){
                    UITextField *tf=[alert textFieldAtIndex:0];
                    if (tf.text.length > 0) {
                        
                        [self showRoundProgressWithTitle:@"请稍后..."];
                        
                        NSMutableDictionary * dic = [NSMutableDictionary  dictionary];
                        dic[@"token"] = allConstMemberToken;
                        dic[@"payUserId"] = allConstMemberid;
                        dic[@"payWay"] = @"1";
                        dic[@"payMoney"] = @(price);
                        dic[@"resId"] = projectId;
                        dic[@"payPass"] = tf.text;
                        
                        [LSHttpTool sendHttpData:@"buyProjectDetail_app_pay.im.lensum" params:dic success:^(id responseObject) {
                            
                            [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
                            
                            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
                            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                                
                                NSMutableDictionary * dict = [NSMutableDictionary dictionary];
                                dict[@"projectId"] = dic[@"resId"];
                                dict[@"userId"] = [USER_DEFAULTS objectForKey:@"userid"];
                                
                                [LSHttpTool sendHttpData:@"projectDetail_app_project.im" params:dict success:^(id responseObject) {
                                    if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {

                                        SearchProjectInfoVC * SeaVC = [[SearchProjectInfoVC alloc]initWithNibName:@"SearchProjectInfoVC" bundle:nil];
                                        SeaVC.dataDict = responseObject[@"data"];
                                        SeaVC.projectData = [NSMutableArray arrayWithArray:responseObject[@"data"][@"commentsList"]];
                                        
                                        [self.navigationController pushViewController:SeaVC animated:YES];
                                        
                                        [self hideBubble];
                                    
                                    }else{

                                        [self showSingleIconBubble:[responseObject objectForKey:@"msg"]];
                                    }
                                    
                                } failure:^(NSError *error) {

                                    [self showSingleIconBubble:@"网络连接错误"];
                                    
                                }];
                     
                            }else{

                               [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
                            
                            }
                            
                            
                        } failure:^(NSError *error) {
                            
                            // 跳转至支付成功页面
                            LSPayResultVC * LSPayResult = [[LSPayResultVC alloc]init];
                            [LSPayResult setCashTypeWithCashFailed];
                            
                            [self hideBubble];
                        }];
                        
                    }else{
                        
                        NSString *strMsg = @"密码不能为空";
                        
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:strMsg delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
                        [alert show];
                        
                    }
                }
            }];
            
            
        }
        
    }
    
}

#pragma mark - alertview

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self.LSPromptAlert dismissViewControllerAnimated:YES completion:nil];
        
        UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UINavigationController *loginNAV = [LoginAndRegister instantiateViewControllerWithIdentifier:@"LoginNav"];
        //充值
        LSRechargeVC * LSRecharge = [[LSRechargeVC alloc]init];
        
        switch (alertView.tag) {
            case 10:
                
                [self presentViewController:loginNAV animated:YES completion:nil];
                
                break;
                
            case 20:
                
                [self.navigationController pushViewController:LSRecharge animated:YES];
                
                break;
                
            case 30:
            {
                
                UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                ForgetPassWord *ForgetPassWord = [LoginAndRegister instantiateViewControllerWithIdentifier:@"forgetpassword"];
                ForgetPassWord.titleStr = @"修改支付密码";
                [self.navigationController pushViewController:ForgetPassWord animated:YES];
                
            }
                break;
                
            default:
                break;
        }
    }
    
    
}
#pragma mark - 网络请求
- (void)startSearch
{
    //NSLog(@"muDicParameters:%@",muDicParameters);
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getProject_app_project.im"];
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            if (paggge == 1) {
                [_mainTableView.mj_header endRefreshing];
                
                _aryInfo = [NSMutableArray arrayWithArray:[dicInfo objectForKey:@"data"][@"record"]];
                
                if (_aryInfo.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }else {
                [_mainTableView.mj_footer endRefreshing];
                NSArray *ary11 = [dicInfo objectForKey:@"data"][@"record"];
                for (int i = 0; i<ary11.count; i++) {
                    NSDictionary *dic1 = ary11[i];
                    [_aryInfo addObject:dic1];
                }
                if (ary11.count == 10) {
                    _mainTableView.mj_footer.hidden = NO;
                }else {
                    _mainTableView.mj_footer.hidden = YES;
                }
                
            }
            
            
            [_mainTableView reloadData];
            
            [self hideBubble];

        }else {
            if (self.searchStr) {
                  _aryInfo = nil;

            }else{

            [_mainTableView reloadData];
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];

            }

        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [_mainTableView.mj_header endRefreshing];
        [_mainTableView.mj_footer endRefreshing];

    }];
}


@end
